# from pprint import pprint
#
# import requests
# import json, pymysql
#
#
# # JSON-RPC请求数据
# data = {
#     "jsonrpc": "2.0",
#     "method": "user.login",
#     "params": {
#         "user": "Admin",
#         "password": "dengcc@521"
#     },
#     "auth": None,
#     "id": 1
# }
#
# # 目标URL
# url = 'http://114.64.228.126:81/api_jsonrpc.php'
#
# # 发送POST请求
# response = requests.post(url, json=data)
# try:
#     response_json = response.json()
#     result = response_json.get('result')
#     print(result)
# except json.JSONDecodeError:
#     print("Received non-JSON response")
#
# ###获取主机信息
# get_host_data = {
#     "jsonrpc": "2.0",
#     "method": "host.get",
#     "params": {
#         "output": ["hostid", "host", "name", "status"]
#     },
#     "auth": "4d3044570edb6326bbbfe9065cdd596a",
#     "id": 1
# }
# response = requests.post(url, json=get_host_data)
# hostinfo = []
# if response.status_code == 200:
#     try:
#         response_json = response.json()
#         if isinstance(response_json, dict) and 'result' in response_json:
#             for item in response_json['result']:
#                 hostinfo.append(item)
#                 # hostip = item.get('host')
#                 # name = item.get('name')
#                 # status = item.get('status')
#
# #             # 连接到MySQL数据库
# #             # 注意：替换为你的数据库连接信息
# #             connection = pymysql.connect(host='127.0.0.1',
# #                                          user='root',
# #                                          password='admin',
# #                                          database='test_api',
# #                                          charset='utf8mb4',
# #                                          cursorclass=pymysql.cursors.DictCursor)
# #
# #             try:
# #                 with connection.cursor() as cursor:
# #                     insert_query = "INSERT INTO deviceinfo (ipaddress, name, status, device_type, community) VALUES (%s, %s, %s, %s, %s)"
# #                     for item in response_json['result']:
# #                         if 'hostid' in item:
# #                             # 注意：这里不使用item.get('hostid', 'HostID not found')，因为'HostID not found'不应该插入数据库
# #                             cursor.execute(insert_query, (
# #                             item.get('host', ''), item.get('name', ''), item.get('status', ''), "交换机", "huawei"))
# #                 connection.commit()
# #                 print("数据插入成功")
# #             finally:
# #                 connection.close()
#     except Exception as e:
#         print(f"发生错误：{e}")
# else:
#     print(f"请求失败，状态码：{response.status_code}")
#
# hostids = [item['hostid'] for item in hostinfo]
#
# ###获取端口信息
# get_interface_data = {
#     "jsonrpc": "2.0",
#     "method": "hostinterface.get",
#     "params": {
#         "output": ["ip", "main", "port", "type"],
#         "hostids": 10325,
#         "search": {
#                         "key_": "net.if"
#                     },
#         "selectItems": ["itemid", "name", "key_", "status"]
#     },
#     "auth": "4d3044570edb6326bbbfe9065cdd596a",
#     "id": 1
# }
# interface_info_data = []
# response = requests.post(url, json=get_interface_data)
# if response.status_code == 200:
#     interface_info = response.json()
#     for item in interface_info.get('result'):  # 使用 get 方法来避免 KeyError
#         if 'items' in item:
#             for i in item['items']:
#                 item_data = {
#                     'itemid': i['itemid'],
#                     'name': i['name'],
#                     'key_': i['key_']
#                 }
#                 # # 将这个字典追加到 interface_info_data 列表中
#                 interface_info_data.append(item_data)
#         #     pprint('items')
#             # interface_info.append(item)
# pprint([item for item in interface_info_data if '/0/' and 'Bits' in item['name']])
# # a = [item for item in interface_info_data if '/0/' in item['name']]
# # pprint(a)
# # itemid = [item.get('itemid') for item in interface_info_data]
# # name = [item.get('name') for item in interface_info_data]
# # key = [item.get('key_') for item in interface_info_data]
# # pprint(itemid)
# # pprint(name)
# # pprint(key)
#     # print(interface_info)
#     # if isinstance(interface_info, dict) and 'result' in interface_info:
#     #     for interface in interface_info['result']:
#     #         print(interface)
#
#
#
######################################
import concurrent
from concurrent.futures import ThreadPoolExecutor

import requests
import json
from pprint import pprint
import pymysql

url1 = "https://absoweb.akdzzt.com/api/auth/login"
param1 = {
    "accountPhone": "18001131582",
    "password": '272b788fffa60e5fffe27e930296a385ade2d45d0534f8738943a4488d2c17b933021a68efb55e8f9bf75949dbc0ce1758f3a07e8dacc9ef7db856290ab9946b3c368326c5ba1533885d8f1090376a0c483090fe4f50f5e0935b8a7eb6ff93ae2a61e985254cb682fe20d722b3d2f2dcdcfe6e8b64edeff5b22326efc34815498c7dd2a4848389e3751f60d58365b3ca018a8c3d0b3a5fb35ee2b0c69d9101b2bb366646251d36f0e5f93965ea4e6f2210ab51bcebcbc54e59c301e4f0dd8b82e0ac6db358ed0e0ff98028bf668c25ca5c884b54162b6aa67296ea032244008895b7b3e96c3db9a668badc74178f1baa445f5f6664775d5eaaa53ddda29da96d'
}
headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36',
    }
session = requests.session()

response = session.post(url=url1, json=param1, headers=headers)
response.raise_for_status()
response_data = response.json()
token = response_data['token']

# url2 = "https://absoweb.akdzzt.com/api/Order/GetOrderPageList"
# page_num = 1
# page_size = 50
#
# db_config = {
#     'host': '127.0.0.1',
#     'user': 'root',
#     'password': 'admin',
#     'database': 'test_api',
#     'charset': 'utf8mb4',
#     'cursorclass': pymysql.cursors.DictCursor
# }
# param2 = {
#             "pageNum": page_num,
#             "pageSize": page_size,
#             "startTime": "2024-08-01",
#             "endTime": "2024-08-31"
# }
# headers_url2 = {
#                 'Authorization': 'Bearer ' + token,
#                 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36'
# }
# connection = pymysql.connect(**db_config)
# try:
#     with connection.cursor() as cursor:
#         while True:
#             response = session.post(url2, json=param2, headers=headers_url2)
#             response.raise_for_status()
#             json_data = response.json()
#
#             if 'data' in json_data and json_data['data'].get('items'):
#                 for item in json_data['data']['items']:
#                     code = item.get('code')
#                     total_price = item.get('totalPrice')
#                     status = item.get('status')
#                     user_Info = item.get('userInfo')
#                     if user_Info:
#                         user_name = user_Info.get('name')
#                         user_type = user_Info.get('userType')
#                         if user_type:
#                             user_type_name = user_type.get('name')
#                         else:
#                             user_type_name = None
#                     else:
#                         user_name = None
#                         user_type_name = None
#                     # sql = "INSERT INTO abso_orderall (code, totalprice, status, user_name, user_type_name) VALUES (%s, %s, %s, %s, %s)"
#                     # cursor.execute(sql, (code, total_price, status, user_name, user_type_name))
#                     # print(code, total_price, status, user_name, user_type_name)
#                 if len(json_data['data']['items']) < page_size:  # 假设如果返回的数据少于一页的大小，则没有更多数据
#                     break
#                 page_num += 1
#                 print(f"第 {page_num}")
#             else:
#                 break
#     connection.commit()
# finally:
#     connection.close()


###----------------#
import pymysql
import requests
from concurrent.futures import ThreadPoolExecutor


def fetch_data(session, url, token, page_num, page_size, start_time, end_time):
    param2 = {
        "pageNum": page_num,
        "pageSize": page_size,
        "startTime": start_time,
        "endTime": end_time
    }
    headers = {
        'Authorization': 'Bearer ' + token,
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36'
    }
    response = session.post(url, json=param2, headers=headers)
    response.raise_for_status()
    return response.json()


def process_data(json_data, cursor):
    if 'data' in json_data and json_data['data'].get('items'):
        for item in json_data['data']['items']:
            code = item.get('code')
            total_price = item.get('totalPrice')
            status = item.get('status')
            user_info = item.get('userInfo')
            user_name = None
            user_type_name = None
            if user_info:
                user_name = user_info.get('name')
                user_type = user_info.get('userType')
                if user_type:
                    user_type_name = user_type.get('name')

            sql = "INSERT INTO abso_orderall (code, totalprice, status, user_name, user_type_name) VALUES (%s, %s, %s, %s, %s)"
            cursor.execute(sql, (code, total_price, status, user_name, user_type_name))


def main():
    url2 = "https://absoweb.akdzzt.com/api/Order/GetOrderPageList"
    page_num = 1
    page_size = 50
    start_time = "2024-08-01"
    end_time = "2024-08-31"

    db_config = {
        'host': '127.0.0.1',
        'user': 'root',
        'password': 'admin',
        'database': 'test_api',
        'charset': 'utf8mb4',
        'cursorclass': pymysql.cursors.DictCursor
    }

    with pymysql.connect(**db_config) as connection:
        with connection.cursor() as cursor:
            with requests.Session() as session:
                with ThreadPoolExecutor(max_workers=5) as executor:
                    while True:
                        future_to_data = {
                            executor.submit(fetch_data, session, url2, token, page_num, page_size, start_time,
                                            end_time): page_num}
                        for future in concurrent.futures.as_completed(future_to_data):
                            page_num = future_to_data[future]
                            data = future.result()
                            process_data(data, cursor)

                            if len(data['data']['items']) < page_size:
                                break

                        if len(data['data']['items']) < page_size:
                            break
                        page_num += 1

        # connection.commit()
        print("数据已插入数据库！")


if __name__ == "__main__":
    main()

